package com.android.topview.watermelon.account.activity

import android.content.Intent
import android.os.Bundle
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.android.topview.watermelon.R
import com.android.topview.watermelon.account.adapter.AccountViewpagerAdapter
import com.android.topview.watermelon.account.viewmodel.AccountViewModel
import com.android.topview.watermelon.base.BaseActivity
import com.android.topview.watermelon.util.setTalkBackFocus
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.activity_account.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class AccountActivity : BaseActivity() {
    private lateinit var mVpAccount: AccountViewModel
    private var mAccountAdapter: AccountViewpagerAdapter? = null
    private val requestDataLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            launch(Dispatchers.IO) {
                if (result.resultCode == RESULT_OK) {
                    val isCostFlag = result.data?.getBooleanExtra("isCost", false)!!
                    if (isCostFlag) {
                        mVpAccount.getCostsLiveData()
                    } else {
                        mVpAccount.getIncomesLiveData()
                    }
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_account)
        mVpAccount = ViewModelProvider(this).get(AccountViewModel::class.java)
        initTab()
        initListener()
        tv_account_title.setTalkBackFocus()
    }

    /**
     * 初始化tab layout的标题
     */
    private fun initTab() {
        mAccountAdapter = AccountViewpagerAdapter(supportFragmentManager)
        vp_account.adapter = mAccountAdapter
        vp_account.addOnPageChangeListener(
            TabLayout.TabLayoutOnPageChangeListener(
                tab_layout_account
            )
        )
        tab_layout_account.addOnTabSelectedListener(
            TabLayout.ViewPagerOnTabSelectedListener(
                vp_account
            )
        )
    }

    /**
     * 初始化监听
     */
    private fun initListener() {
        val btnAddAccount = findViewById<ImageView>(R.id.iv_add_account)
        btnAddAccount.setOnClickListener {
            val intent = Intent(this, AddAccountActivity::class.java)
            requestDataLauncher.launch(intent)
        }
        iv_account_back.setOnClickListener {
            finish()
        }
    }

}